package com.jonniespratley.flexdatabasemanager.view.components.databases
{
	import com.jonniespratley.flexdatabasemanager.events.databases.GetDatabasesEvent;
	import com.jonniespratley.flexdatabasemanager.events.databases.SelectedDatabaseEvent;
	import com.jonniespratley.flexdatabasemanager.events.tables.SelectedTableEvent;
	import com.jonniespratley.flexdatabasemanager.model.ModelLocator;
	import com.jonniespratley.flexdatabasemanager.vo.*;
	
	import mx.controls.Tree;
	import mx.events.ListEvent;
	import mx.events.TreeEvent;

	public class DatabaseTablesFieldsTree extends Tree
	{
		[Bindable] private var model:ModelLocator = ModelLocator.getInstance();
		[Bindable] private var currentDatabase:DatabaseVO;
		[Bindable] private var currentTable:TableVO;
		
		public function DatabaseTablesFieldsTree()
		{
			super();
			this.addEventListener( ListEvent.CHANGE, changeEvt );
			this.addEventListener(TreeEvent.ITEM_OPEN, itemOpen );
			this.init();
		}
		
		private function init():void
		{
			this.getDatabases();
			this.dataProvider = model.databaseCollection;
		}
		
		private function getDatabases():void
		{
			var evt:GetDatabasesEvent = new GetDatabasesEvent();
				evt.dispatch();
		}
		
		
		private function changeEvt( event:Event ):void 
		{
			var type:String = event.currentTarget.selectedItem.data;
			var tree:Tree = Tree( event.currentTarget );
			
			if ( event.currentTarget.selectedItem.aType == 'database' )
			{
				selectedDatabase( event.currentTarget.selectedItem );
			} else if ( event.currentTarget.selectedItem.aType == 'table' )
			{
				selectedTable( event.currentTarget.selectedItem );
				//selectedDatabase( tree.getParentItem( event.currentTarget.selectedItem ) );
			} else if ( event.currentTarget.selectedItem.aType == 'field' )
			{
				//
			}
			
		}
			
		private function selectedDatabase( database:DatabaseVO ):void
		{			
			var evt:SelectedDatabaseEvent = new SelectedDatabaseEvent( database );
				evt.dispatch();
				
			this.currentDatabase = database;
		}
		
		private function selectedTable( table:TableVO ):void
		{			
			var evt:SelectedTableEvent = new SelectedTableEvent( currentDatabase, currentTable );
				evt.dispatch();
				
			this.currentTable = table;
		}
		
		private function itemOpen( event:TreeEvent ):void
		{
			if ( event.item.aType == 'database' )
			{
				this.currentDatabase = new DatabaseVO( event.item );
				this.selectedDatabase( currentDatabase );
				
			} else if ( event.item.aType  == 'table' )
			{
				this.currentTable = new TableVO( event.item );
				this.selectedTable( currentTable );
			}
		}
	}
}